package com.cg.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class MyCustomThreadPool {

    @Bean(name = "async-executor-spring")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(1);
        //线程池维护线程最大值，只有在缓冲队列满了之后才会折你去哪个超过核心线程数的线程
        threadPoolTaskExecutor.setMaxPoolSize(1);
        //缓存队列
        threadPoolTaskExecutor.setQueueCapacity(20);
        //空闲时间，当超过了核心线程数之外的线程在空闲时间到达之后会被消耗
        threadPoolTaskExecutor.setKeepAliveSeconds(200);
        //异步方法内部线程名称
        threadPoolTaskExecutor.setThreadNamePrefix("async-executor-spring");

        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return TtlExecutors.getTtlExecutor(threadPoolTaskExecutor);
    }

}
